18. System CPU Percent

getSysCpuPercent()

10# Example - Class ProcessParser - GetSysCpuPercent

This function reads raw data from the /proc/stat file. This file contains information on overall cpu usage, as well stats for individual cores. Other functions ultimately use this data to calculate total, active, and idle CPU time.

Every token from the raw data is stored as an individual value in a string vector.

vector<string> ProcessParser::getSysCpuPercent(string coreNumber)
{
    // It is possible to use this method for selection of data for overall cpu or every core.
    // when nothing is passed "cpu" line is read
    // when, for example "0" is passed  -> "cpu0" -> data for first core is read
    string line;
    string name = "cpu" + coreNumber;
    ifstream stream = Util::getStream((Path::basePath() + Path::statPath()));
    while (std::getline(stream, line)) {
        if (line.compare(0, name.size(),name) == 0) {
            istringstream buf(line);
            istream_iterator<string> beg(buf), end;
            vector<string> values(beg, end);
            // set of cpu data active and idle times;
            return values;
        }
    }
    return (vector<string>());
}

These functions for calculating active and idle time are a direct extension of the system CPU percentage. They sort and categorize a newly created string vector, which contains parsed raw data from file. Because most of the data is recorded as time, we are select and sum all active and idle time.

float get_sys_active_cpu_time(vector<string> values)
{
    return (stof(values[S_USER]) +
            stof(values[S_NICE]) +
            stof(values[S_SYSTEM]) +
            stof(values[S_IRQ]) +
            stof(values[S_SOFTIRQ]) +
            stof(values[S_STEAL]) +
            stof(values[S_GUEST]) +
            stof(values[S_GUEST_NICE]));
}

float get_sys_idle_cpu_time(vector<string>values)
{
    return (stof(values[S_IDLE]) + stof(values[S_IOWAIT]));
}